package com.ruoyi.elastic.config;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;
/**
 * @Description: TODO
 * @CreateTime: 2023-01-01  15:36
 * @Author: chaozi
 * @Version: 1.0
 */
@Configuration
public class ElasticClient {
    @Value("${elastic.url}")
    private String esUrl;


    @Value("${elastic.username}")
    private String username;
    @Value("${elastic.password}")
    private String password;
    //通用设置项
    public static final RequestOptions COMMON_OPTIONS;

    static {
        RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();

        COMMON_OPTIONS = builder.build();
    }


    @Bean
    RestHighLevelClient configRestHighLevelClient() throws Exception {

        RestHighLevelClient client = null;
        try {
            String[] esUrlArr = esUrl.split(",");

            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            if("".equals(username)&&"".equals(password)){
                credentialsProvider.setCredentials(AuthScope.ANY,
                        new UsernamePasswordCredentials(username, password));
            }



            List<HttpHost> httpHosts = new ArrayList<>();
            for(String es : esUrlArr){
                String[] esUrlPort = es.split(":");
                httpHosts.add(new HttpHost(esUrlPort[0], Integer.parseInt(esUrlPort[1]), "http"));
            }

            client= new RestHighLevelClient(
                    RestClient.builder(httpHosts.toArray(new HttpHost[0])).setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                        public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                            httpClientBuilder.disableAuthCaching();
                            return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                        }
                    })
            );
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return client;
    }
}
